package cn.edu.ldu.views.main;

import cn.edu.ldu.controller.GroupController;
import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.ChatHistoryEntity;
import cn.edu.ldu.entity.ChatMemberEntity;
import cn.edu.ldu.entity.GroupChatEntity;
import cn.edu.ldu.entity.UserAccountEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.*;
import cn.edu.ldu.views.main.util.ListModel;
import cn.edu.ldu.views.operator.Friends;
import cn.edu.ldu.views.operator.History;
import cn.edu.ldu.views.operator.Members;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author DYZ
 */
public class GroupChatUI extends javax.swing.JPanel {
    /**
     * Creates new form ChatUI
     */
    public GroupChatUI(int width, int height, GroupChatEntity groupChatEntity) {
        group = groupChatEntity;
        initComponents(group);
        this.setSize(width,height);
        this.setVisible(true);
    }
    //获得群聊成员
    public void setChatMember(List<ChatMemberEntity> members){

        member = new ListModel();
        for (int i = 0; i< members.size(); i++){
            member.addElement(members.get(i).getMyAlias(),members.get(i).getUserId(),1);
        }
        listMember.setModel(member);
        jScrollPane1.setViewportView(listMember);
        jScrollPane1.updateUI();
    }

    //接受信息
    public void receiveGroupMsg(ChatHistoryEntity msg){
        //得到群聊好友实体
        talker = new ChatMemberEntity();
        talker = GroupController.getGroupMenber(msg.getSenderId());
        txtMsg.append(Translate.stampToDate(msg.getSendTime())+"\n"+talker.getMyAlias()+":"+msg.getContent()+"\n");
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents(GroupChatEntity groupChatEntity) {

        jPanel1 = new javax.swing.JPanel();
        labGroupId = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listMember = new javax.swing.JList<>();
        jPanel3 = new javax.swing.JPanel();
        btnBold = new javax.swing.JButton();
        btnCheckMsg = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtSend = new javax.swing.JTextArea();
        btnSend = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtMsg = new javax.swing.JTextArea();
        member = new cn.edu.ldu.views.main.util.ListModel();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 0, 0)));

        labGroupId.setText(groupChatEntity.getGroupName());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addComponent(labGroupId)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 297, Short.MAX_VALUE)
                                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(labGroupId))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("群成员"));

        listMember.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });

        listMember.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnlistMenberMouseClicked(evt);
            }
        });

        jScrollPane1.setViewportView(listMember);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
        );

        add(jPanel2, java.awt.BorderLayout.LINE_END);

        btnBold.setText("A");
        btnBold.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnBlodMouseClicked(evt);
            }
        });

        btnCheckMsg.setText("查看聊天记录");
        btnCheckMsg.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCheckMsgMouseClicked(evt);
            }
        });

        txtSend.setColumns(20);
        txtSend.setRows(5);
        txtSend.setLineWrap(true);
        jScrollPane3.setViewportView(txtSend);

        btnSend.setText("发送");
        btnSend.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSendMouseClicked(evt);
            }
        });


        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(btnBold)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 338, Short.MAX_VALUE)
                                .addComponent(btnCheckMsg))
                        .addComponent(jScrollPane3)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnSend))
        );
        jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnBold)
                                        .addComponent(btnCheckMsg))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                                .addComponent(btnSend))
        );

        add(jPanel3, java.awt.BorderLayout.PAGE_END);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("聊天界面"));

        txtMsg.setColumns(20);
        txtMsg.setRows(5);
        txtMsg.setEnabled(false);
        jScrollPane2.setViewportView(txtMsg);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
        );

        add(jPanel4, java.awt.BorderLayout.CENTER);
    }// </editor-fold>

    /**
     * 字体加粗
     */
    private void btnBlodMouseClicked(MouseEvent evt){
        if(evt.getClickCount() == 1)
            txtSend.setFont(new Font("宋体",Font.BOLD,15));
        else
            txtSend.setFont(new Font("宋体",0,15));
    }

    /**
     * 查询历史消息
     */
    private void btnCheckMsgMouseClicked(MouseEvent evt){
        InetAddress remoteAddr = null;
        try {
            remoteAddr = InetAddress.getByName(Consts.ipv4);
            //创建UDP套件字
            DatagramSocket clientSocket = null;
            clientSocket = new DatagramSocket();

            //构建用户查看信息记录信息
            Protocol protocol = new Protocol();
            protocol.setKey("GetChatHistory");
            protocol.setToken(UserController.getToken());

            ChatHistoryEntity chatHistoryEntity = new ChatHistoryEntity();
            chatHistoryEntity.setTalkerId(group.getId());
            chatHistoryEntity.setSenderId(UserController.getUserEntity().getId());

            //转字符
            protocol.setData(JSON.toJSONString(chatHistoryEntity));
            data = Translate.ObjectToByte(protocol);

            //定义查看历史信息报文
            DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
            clientSocket.send(packet);
            L.OK(packet,GroupChatUI.class);

            byte[] receiveData = new byte[8096];
            packet = new DatagramPacket(receiveData,receiveData.length,remoteAddr,Consts.port);
            clientSocket.receive(packet);

            //查看发送结果
            L.OK(packet,GroupChatUI.class);

            Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());
            pro.key();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 双击好友出现信息界面
     */
    private void btnlistMenberMouseClicked(MouseEvent evt){
        if(evt.getClickCount() == 2){
            friend = new ChatMemberEntity();
            friend = GroupController.getGroupMenber(member.getUserIds(listMember.getSelectedIndex()));
            L.OK(friend,GroupChatUI.class);
            new Members(friend).setVisible(true);
        }
    }

    /**
     * 发送信息
     */
    private void btnSendMouseClicked(MouseEvent evt){
        try {
            DatagramSocket clientSocket = Ports.getCommon();
            Protocol protocol = new Protocol();
            protocol.setKey("ChatInGroup");
            protocol.setToken(UserController.getToken());

            ChatHistoryEntity che = new ChatHistoryEntity();
            che.setSenderId(UserController.getUserEntity().getId());
            che.setTalkerId(group.getId());
            che.setMsg(1);
            che.setContent(txtSend.getText());
            che.setIsGroup(1);
            protocol.setToken(UserController.getToken());

            protocol.setData(JSON.toJSONString(che));

            byte[] data = Translate.ObjectToByte(protocol);
            DatagramPacket packet = new DatagramPacket(data,data.length, InetAddress.getByName(Consts.ipv4),Consts.port);
            clientSocket.send(packet);
            L.OK(packet,GroupChatUI.class);

            //在面板显示
            txtMsg.append(Util.nowDate()+"\n");
            txtMsg.append(UserController.getUserEntity().getUsername()+":"+txtSend.getText()+"\n");
            txtSend.setText("");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnBold;
    private javax.swing.JButton btnCheckMsg;
    private javax.swing.JButton btnSend;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel labGroupId;
    private javax.swing.JList<String> listMember;
    private javax.swing.JTextArea txtMsg;
    private javax.swing.JTextArea txtSend;
    private GroupChatEntity group;
    private cn.edu.ldu.views.main.util.ListModel member;
    private ChatMemberEntity friend;
    private ChatMemberEntity talker;
    private byte[] data = new byte[8096];
    // End of variables declaration
}